/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.controller;

import com.xnck.mfpms.annotation.Permission;
import com.xnck.mfpms.entity.RoleInfo;
import com.xnck.mfpms.entity.UserInfo;
import com.xnck.mfpms.exception.ValidateException;
import com.xnck.mfpms.service.RoleService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/pms/role")
public class SysRoleController extends BaseController{
    private static final Logger log = Logger.getLogger(SysRoleController.class);

    @Autowired
    private RoleService roleService;

    /**
     * 资源列表
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_role_list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getList(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/role/list");
        return mv;
    }

    /**
     * 资源总数
     * @param request
     * @param response
     * @param name
     */
    @Permission("url_sys_pms_role_list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void postList(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "name")String name){
        try {
            int count = roleService.getsCount(name);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 资源主体
     * @param request
     * @param response
     * @param pageSize
     * @param beginIndex
     * @param name
     * @param orderName
     * @param orderType
     * @return
     */
    @Permission("url_sys_pms_role_listbody")
    @RequestMapping(value = "/listbody", method = RequestMethod.POST)
    public ModelAndView postBody(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "limit")int pageSize,
                                 @RequestParam(value = "offset")int beginIndex,
                                 @RequestParam(value = "name")String name,
                                 @RequestParam(value = "sort", required = false)String orderName,
                                 @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/role/listbody");
        try {
            List<RoleInfo> roles = roleService.gets(name, orderName, orderType, pageSize, beginIndex);
            mv.addObject("roles", roles);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        return mv;
    }

    /**
     * 创建资源
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_role_create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getCreate(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/role/create");
        return mv;
    }

    /**
     * 创建资源
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_role_create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void postCreate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            roleService.create(curUserId, displayName, enable);
            responseSuccessMsg(response, null, "添加成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 修改资源
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_role_update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView getUpdate(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String roleId){
        ModelAndView mv = new ModelAndView("/sys/pms/role/update");
        try {
            RoleInfo role = roleService.get(roleId);
            mv.addObject("role", role);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 修改资源
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_role_update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public void postUpdate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "id")String roleId,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            roleService.update(roleId, displayName, enable);
            responseSuccessMsg(response, null, "修改成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 批量删除
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_role_multidel")
    @RequestMapping(value = "/multidel", method = RequestMethod.POST)
    public void postMulti(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "ids")String roleIds){
        try {
            roleService.deletes(roleIds);
            responseSuccessMsg(response, null, "删除成功");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 设置人员
     */
    @Permission("url_sys_pms_role_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.GET)
    public ModelAndView getSetUser(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String roleId){
        ModelAndView mv = new ModelAndView("/sys/pms/role/setuser");
        try {
            RoleInfo role = roleService.get(roleId);
            mv.addObject("role", role);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置人员
     */
    @Permission("url_sys_pms_role_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.POST)
    public void postSetUser(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "rid")String roleId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String userIdStr){
        try {
            if (isJoin){
                roleService.cancelJoinUser(roleId, userIdStr);
            }
            else {
                roleService.joinUser(roleId, userIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 人员列表总数
     */
    @Permission("url_sys_pms_role_userlistcount")
    @RequestMapping(value = "/userlistcount", method = RequestMethod.POST)
    public void postUserListCount(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "selflag", required = false)boolean isJoin,
                                  @RequestParam(value = "name")String userName,
                                  @RequestParam(value = "rid")String roleId){
        try {
            int count;
            if (isJoin){
                count = roleService.getJoinedUsersCount(roleId, userName);
            }
            else {
                count = roleService.getNoJoinUsersCount(roleId, userName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 人员列表主体
     */
    @Permission("url_sys_pms_role_userlistbody")
    @RequestMapping(value = "/userlistbody", method = RequestMethod.POST)
    public ModelAndView postUserListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String userName,
                                         @RequestParam(value = "rid")String roleId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/role/userlistbody");
        try {
            List<UserInfo> users;
            if (isJoin){
                users = roleService.getJoinedUsers(roleId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                users = roleService.getNoJoinUsers(roleId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("users", users);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }


    /**
     * 设置权限
     * @param request
     * @param response
     * @param roleId
     * @return
     */
    @Permission("url_sys_pms_role_setaction")
    @RequestMapping(value = "/setaction", method = RequestMethod.GET)
    public ModelAndView getSetAction(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam(value = "id")String roleId){
        ModelAndView mv = new ModelAndView("/sys/pms/role/setaction");
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            RoleInfo role = roleService.get(roleId);
            mv.addObject("role", role);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置权限
     * @param request
     * @param response
     * @param roleId
     * @param actionIdStr
     */
    @Permission("url_sys_pms_role_setaction")
    @RequestMapping(value = "/setaction", method = RequestMethod.POST)
    public void postSetAction(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "rid")String roleId,
                              @RequestParam(value = "ids")String actionIdStr){
        try {
            roleService.joinAction(roleId, actionIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 权限树
     * @param request
     * @param response
     * @param roleId
     */
    @Permission("url_sys_pms_role_actionnodes")
    @RequestMapping(value = "/actionnodes", method = RequestMethod.POST)
    public void postActionNodes(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam(value = "id")String roleId){
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            List<Map<String, Object>> nodes = roleService.getActionNodes(roleId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 设置规则
     * @param request
     * @param response
     * @param roleId
     * @return
     */
    @Permission("url_sys_pms_role_setrule")
    @RequestMapping(value = "/setrule", method = RequestMethod.GET)
    public ModelAndView getSetRule(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String roleId){
        ModelAndView mv = new ModelAndView("/sys/pms/role/setrule");
        try {
            RoleInfo role = roleService.get(roleId);
            mv.addObject("role", role);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置规则
     * @param request
     * @param response
     * @param roleId
     * @param ruleIdStr
     */
    @Permission("url_sys_pms_role_setrule")
    @RequestMapping(value = "/setrule", method = RequestMethod.POST)
    public void postSetRule(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "rid")String roleId,
                            @RequestParam(value = "ids")String ruleIdStr){
        try {
            roleService.joinRule(roleId, ruleIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 规则树
     * @param request
     * @param response
     * @param roleId
     */
    @Permission("url_sys_pms_role_rulenodes")
    @RequestMapping(value = "/rulenodes", method = RequestMethod.POST)
    public void postRuleNodes(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "id")String roleId){
        try {
            List<Map<String, Object>> nodes = roleService.getRuleNodes(roleId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 设置菜单
     * @param request
     * @param response
     * @param roleId
     * @return
     */
    @Permission("url_sys_pms_role_setmenu")
    @RequestMapping(value = "/setmenu", method = RequestMethod.GET)
    public ModelAndView getSetMenu(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String roleId){
        ModelAndView mv = new ModelAndView("/sys/pms/role/setmenu");
        try {
            RoleInfo role = roleService.get(roleId);
            mv.addObject("role", role);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置菜单
     * @param request
     * @param response
     * @param roleId
     * @param menuIdStr
     */
    @Permission("url_sys_pms_role_setmenu")
    @RequestMapping(value = "/setmenu", method = RequestMethod.POST)
    public void postSetMenu(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "rid")String roleId,
                            @RequestParam(value = "ids")String menuIdStr){
        try {
            roleService.joinMenu(roleId, menuIdStr);
            responseSuccessMsg(response, null, "关联成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 菜单树
     * @param request
     * @param response
     * @param roleId
     */
    @Permission("url_sys_pms_role_menunodes")
    @RequestMapping(value = "/menunodes", method = RequestMethod.POST)
    public void postMenuNodes(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "id")String roleId){
        try {
            List<Map<String, Object>> nodes = roleService.getMenuNodes(roleId);
            responseSuccessMsg(response, nodes, "ok");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }
}
